package com.alibaba.utils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 根据文件扩展名自动解析对应的 MinIO Bucket 名称
 * 支持直接传入文件名或后缀
 *
 * @author ZhouYaDong
 * @date 2025/9/23
 */
public class BucketResolver {

    private static final Map<String, String> EXTENSION_BUCKET_MAP = new HashMap<>();

    static {
        // 图片
        Arrays.asList("jpg","jpeg","png","gif","webp")
                .forEach(ext -> EXTENSION_BUCKET_MAP.put(ext, "images"));
        // 视频
        Arrays.asList("mp4","avi","mov","mkv")
                .forEach(ext -> EXTENSION_BUCKET_MAP.put(ext, "videos"));
        // 文档
        Arrays.asList("pdf","doc","docx","xls","xlsx","ppt","pptx")
                .forEach(ext -> EXTENSION_BUCKET_MAP.put(ext, "documents"));
        // 音频
        Arrays.asList("mp3","wav","flac")
                .forEach(ext -> EXTENSION_BUCKET_MAP.put(ext, "audios"));
        // 压缩包
        Arrays.asList("zip","rar","tar","gz","7z")
                .forEach(ext -> EXTENSION_BUCKET_MAP.put(ext, "archives"));
    }

    /**
     * 根据文件后缀自动获取对应的 bucket 名称
     * @param extension 文件后缀(不带点)，如 "pdf"
     * @return bucket 名称，如果未知返回 "others"
     */
    public static String resolveBucketByExtension(String extension) {
        if (extension == null || extension.isBlank()) {
            return "others";
        }
        return EXTENSION_BUCKET_MAP.getOrDefault(extension.toLowerCase(), "others");
    }

    /**
     * 根据完整文件名自动解析 bucket 名称
     * @param fileName 例如 "test.PDF" 或 "image.png"
     * @return bucket 名称，如果无后缀或未知类型返回 "others"
     */
    public static String resolveBucketByFileName(String fileName) {
        if (fileName == null || fileName.isBlank()) {
            return "others";
        }
        int dotIndex = fileName.lastIndexOf('.');
        if (dotIndex < 0 || dotIndex == fileName.length() - 1) {
            return "others";
        }
        String ext = fileName.substring(dotIndex + 1);
        return resolveBucketByExtension(ext);
    }

    /**
     * 兼容旧方法：若传入后缀或文件名都能识别
     * @param input 既可以是文件名也可以是后缀
     */
    public static String resolveBucket(String input) {
        if (input == null || input.isBlank()) {
            return "others";
        }
        // 判断是否包含点，包含则认为是文件名
        return input.contains(".") ? resolveBucketByFileName(input)
                : resolveBucketByExtension(input);
    }

    private BucketResolver() {
        // 工具类禁止实例化
    }
}
